package com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.myprofile

import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.helasasa.maxfunds.lineofcredit.cashloan.ProjectApplication
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.IApiProcessCallback
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.createApiAction
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.doPostRequest
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.user.mainProcessFormat
import org.json.JSONArray
import org.json.JSONObject

class MyProfileGhanaViewModel : ViewModel() {

    private val _loadingResult = MutableLiveData<Boolean>()
    val loadingResult: LiveData<Boolean> = _loadingResult

    private val _pageDetailResult = MutableLiveData<MyProfileGhanaTypeResult>()
    val pageDetailResult: LiveData<MyProfileGhanaTypeResult> = _pageDetailResult

    private val _mainProcessResult = MutableLiveData<MyProfileGhanaMainProcessResult>()
    val mainProcessResult: LiveData<MyProfileGhanaMainProcessResult> = _mainProcessResult

    private val _nextRouterResult =
        MutableLiveData<MyProfileGhanaNextRouterResult<AppCompatActivity>>()
    val nextRouterResult: LiveData<MyProfileGhanaNextRouterResult<AppCompatActivity>> =
        _nextRouterResult

    private var stepIndex = 0

    /** 查询主流程接口 */
    fun mainProcess() {
        _loadingResult.value = true

        val context = ProjectApplication.context
        val action = hashMapOf<String, Any>().createApiAction()
        action["path"] = "D50PrK3UELaosdHcVCL7A"

        context.doPostRequest(action, object : IApiProcessCallback {
            override fun onApiReady() {
            }

            override fun onApiDone(jsonObject: JSONObject) {
                _loadingResult.value = false
                val obj = jsonObject.optJSONObject("obj")
                _mainProcessResult.value = MyProfileGhanaMainProcessResult(success = obj)
            }

            override fun onApiError(code: String, errMsg: String) {
                _loadingResult.value = false

                _mainProcessResult.value =
                    MyProfileGhanaMainProcessResult(error = errMsg)
            }
        })

    }

    /**
     * 拉状态回显
     */
    fun pageDetail() {
        _loadingResult.value = true

        val context = ProjectApplication.context
        val action = hashMapOf<String, Any>().createApiAction()
        action["path"] = "D50PrK3UELaosdHcVCL7A"

        context.doPostRequest(action, object : IApiProcessCallback {
            override fun onApiReady() {
            }

            override fun onApiDone(jsonObject: JSONObject) {
                _loadingResult.value = false

                val obj = jsonObject.optJSONObject("obj") ?: JSONObject()
                val applyStatus = obj.optString("applyStatus")
                val hadApply = (applyStatus !== "NO")
                val steps = obj.optJSONArray("steps") ?: JSONArray()
                val allSteps = obj.optJSONArray("allSteps") ?: JSONArray()
                val allStepTitles = obj.optJSONArray("allStepTitles") ?: JSONArray()

                val list = mutableListOf<JSONObject>()
                for (index in 0 until allStepTitles.length()) {
                    val curStep = allSteps[index] as String
                    val stepTitle = allStepTitles[index] as String
                    val item = JSONObject()
                    item.put("step", curStep)
                    item.put("stepTitle", stepTitle)
                    item.put("done", "YES")

                    // 判断是否完成
                    val refStep = allSteps[index] as String
                    for (si in 0 until steps.length()) {
                        val step = steps[si] as String
                        if (step == refStep) {
                            item.put("done", "NO")
                            break
                        }
                    }
                    list.add(item)
                }

                _pageDetailResult.value =
                    MyProfileGhanaTypeResult(items = list, hadApply = hadApply)
            }

            override fun onApiError(code: String, errMsg: String) {
                _loadingResult.value = false

                _mainProcessResult.value =
                    MyProfileGhanaMainProcessResult(error = errMsg)
            }
        })

    }

    /**
     * 查询步骤回显信息
     */
    fun pageDetailByStep(step: String) {
        _loadingResult.value = true

        val context = ProjectApplication.context
        val action = hashMapOf<String, Any>().createApiAction()
        action["path"] = "bpq8RBaywBfGQOkzlkMQuQ"
        action["type"] = step

        context.doPostRequest(action, object : IApiProcessCallback {
            override fun onApiReady() {
            }

            override fun onApiDone(jsonObject: JSONObject) {
                _loadingResult.value = false

                val obj = jsonObject.optJSONArray("obj") ?: JSONArray()
                val list = mutableListOf<JSONObject>()

                if (step.contains("contact_info", true)) {
                    for (index in 0 until obj.length()) {
                        val section = obj[index] as JSONArray
                        for (secIndex in 0 until section.length()) {
                            val item = section[secIndex] as JSONObject
                            if ((index > 0) and (secIndex == 0)) {
                                item.put("title", "YES")
                            }
                            list.add(item)
                        }
                    }
                } else {
                    for (index in 0 until obj.length()) {
                        val item = obj[index] as JSONObject
                        list.add(item)
                    }
                }
                _pageDetailResult.value = MyProfileGhanaTypeResult(items = list)
            }

            override fun onApiError(code: String, errMsg: String) {
                _loadingResult.value = false

                _pageDetailResult.value = MyProfileGhanaTypeResult(error = errMsg)
            }
        })

    }

    /** 页面跳转 */
    fun nextRouter(jsonObject: JSONObject) {
        // 判断下一步
        val nextRouterResult = jsonObject.mainProcessFormat(fromMyProfile = true)
        if (nextRouterResult.nextRouter != null) {
            _nextRouterResult.value =
                MyProfileGhanaNextRouterResult(nextPage = nextRouterResult.nextRouter)
        }
    }
}